#import('dart:html');
#import("dart:json");
#source('PostsReq.dart');
#source('MakeNewPost.dart');
#source('TagsReq.dart');
#source('PostSend.dart');
#source('SideBar.dart');
#source('GetPostsByTag.dart');
#source('PostReqByTag.dart');
#source('Windows.dart');
#source('GetPostsByUsers.dart');
#source('PostReqByUsers.dart');
#source('GetPostsByDate.dart');
#source('PostReqByDates.dart');

class Blog {
  
  String _url;
  String currUser = null;
  PostsReq postsRequest;
  PostSend postSend;
  MakeNewPost newPostMaker;
  GetPostsByTag getPostsByTag;
 
  SideBar bar;

	Queue prevPage;
    Queue currPage;
	Queue nextPage;
	
	var isFirstTime = true;
  
  Blog(String url) {
	_url = url;
	bar = new SideBar(this);
	postsRequest = new PostsReq(this ,url);
	postSend = new PostSend(this, url);
	newPostMaker = new MakeNewPost(this);
	getPostsByTag = new GetPostsByTag(this, bar, url);
  }
  
	void showView(){
		//checkCookie();
		bar.showSideBar(currUser);
		showPosts();
		document.query('#prevButton').on.click.add((events) => getPrevPage());
		document.query('#nextButton').on.click.add((events) => getNextPage());
		if(isLogginedIn()){
		  showSignOutBar();
		}
		else{
		  showSignInBar();
		}
	}
 
  // show next page
	void getNextPage(){
	   if(nextPage == null || nextPage.isEmpty()){
	      //window.alert("ERROR in getNextPage() : nextPage == null || nextPage.isEmpty()");
	      return;
	    }
		
		// disable next button
		disableNextButton();

		prevPage = currPage;
		currPage = nextPage;
		// show current page
		showCurrPage();
		
		nextPage = new Queue();
		// fills the next page queue whith posts form server
		postsRequest.loadNextPage(nextPage);
	}

	// show prev page
	void getPrevPage(){
	   if(prevPage == null || prevPage.isEmpty()){
	      //window.alert("ERROR in getPrevPage() : prevPage == null || prevPage.isEmpty()");
	      return;
	    }
		disablePrevButton();
		
		nextPage = currPage;
		currPage = prevPage;
		
		// show current page
		showCurrPage();
		
		prevPage = new Queue();
		// fill the prev page
		postsRequest.loadPrevPage(prevPage);
	}
	
	void showPosts(){
		isFirstTime = true;
		prevPage = new Queue();
		currPage = new Queue();
		nextPage = new Queue();
		disablePrevButton();
		disableNextButton();
		postsRequest.loadCurrPage(currPage);
	}

  //
  // this function is invoked by PostReq object
  //
	void updateButtons(){
		if(isFirstTime){
			isFirstTime = false;
			if(currPage.length == 0){
				noPosts();
				return;
			}
			showCurrPage();
			postsRequest.loadNextPage(nextPage);
		}

		//window.alert("prev:\n$prevPage\ncurr\n$currPage\nnext:\n$nextPage");

	    balancePages();

  		if(nextPage.length > 0){
  			enableNextButton();
  		}

  		if(prevPage.length > 0){
  			enablePrevButton();
  		}
    }
	
	void noPosts(){
		document.query('#posts').innerHTML = '<center>No Posts...</center>';
	}

	void balancePages(){	
		if(prevPage == null || prevPage.isEmpty()){
			// no need for balance
			return;
	    }

		while(prevPage.length < 10 && currPage.length > 0){
			prevPage.add(currPage.removeFirst());
		}

		while(currPage.length < 10 && nextPage.length > 0){
			currPage.add(nextPage.removeFirst());
		}
	}

	void enableNextButton(){
		document.query('#nextButton').attributes['class'] = 'next';
	}
	
	void disableNextButton(){
		document.query('#nextButton').attributes['class'] = 'nextdisabled';
	}
	
	void enablePrevButton(){
		document.query('#prevButton').attributes['class'] = 'previous';
	}
	
	void disablePrevButton(){
		document.query('#prevButton').attributes['class'] = 'prevdisabled';
	}

	void showCurrPage(){
		String elemStart = '<div class="post">';
		String elemEnd = '</div>';
		String posts="";
		String name;
		
		Iterator i = currPage.iterator();
		while(i.hasNext()){
		  Map postDO = i.next();
		  
		  String title = postDO['title'];
		  String content = postDO['content'];
		  String date = postDO['pubDate'];
		  String user = postDO['user'];
		  String tags = postDO['tags'];
		  Date dDate = new Date.fromString(date);
		  
		  List lTags = tags.split(" ");
		  tags = '';
		  for(int i = 0; i < lTags.length; i++){
			tags += lTags[i];
			if(i < lTags.length - 1){
				tags += ' / ';
			}
		  }
		  String tgs = '';
		  if(tags.length > 0)
			tgs = '<div style = "border-top:1px dashed #ccc; font-weight:500; color:#0064cd">' + tags + '</div>';
		  
		  posts += elemStart + 
				   '<h3> <xmp style = "font-weight:800">' + title + '</xmp></h3>' +
				   '<xmp>' + content  + '</xmp>' +
				   '<br/><small><b>' + user + '</b> at ' + dateToString(date) + '</small></br>' + tgs + elemEnd;
		}
		document.query('#posts').innerHTML = posts;
	}
	

	String dateToString(String sDate){
		Date d = new Date.fromString(sDate);
		String day = d.day.toString();
		String year = d.year.toString();
		String hours = d.hours.toString();
		String minutes = d.minutes.toString();
		
		if(d.day/10 < 1)
		  day = '0' + day;
		if(d.hours/10 < 1)
		  hours = '0' + hours;
		if(d.minutes/10 < 1)
		  minutes = '0' + minutes;
		
		
		String month;
		switch(d.month){
			case 1 : month = 'Jan'; 
			break;
			case 2 : month = 'Feb'; 
			break;
			case 3 : month = 'Mar'; 
			break;
			case 4 : month = 'Apr'; 
			break;
			case 5 : month = 'May'; 
			break;
			case 6 : month = 'Jun'; 
			break;
			case 7 : month = 'Jul'; 
			break;
			case 8 : month = 'Aug'; 
			break;
			case 9 : month = 'Sep'; 
			break;
			case 10 : month = 'Oct'; 
			break;
			case 11 : month = 'Nov'; 
			break;
			case 12 : month = 'Dec'; 
			break;			
		}
		String str =  hours + ':' + minutes + '  ' + day + ' ' + month + ' ' + year;
		return str;
	}
	
  
	String getLastDate(){
		if(currPage.isEmpty())
		  return null;

		Map postDO = currPage.last();
		return postDO['pubDate'];
	}
  
	String getFirstDate(){
		if(currPage.isEmpty())
		  return null;
		  
		Map postDO = currPage.first();
		return postDO['pubDate'];
	}
	
	String getLastID(){
		if(currPage.isEmpty())
		  return null;

		Map postDO = currPage.last();
		return postDO['id'];
	}
  
	String getFirstID(){
		if(currPage.isEmpty())
		  return null;
		  
		Map postDO = currPage.first();
		return postDO['id'];
	}	

  //--------------------------------------------------
  void addPostToServer(Map newPost){
    postSend.sendPost(newPost);
  }

    void signIn(){
  		var signingUser = document.query('#signin');
  		if(isValidName(signingUser.value)){
		  currUser = signingUser.value;
  		  bar.showNewPostBtn();
  		  setCookie(currUser);
		  showSignOutBar();
  		}
  		else{
  		  window.alert("Please login with a valid name");
  		}
  	}
	
	void signOut(){
		currUser = null;
		bar.hideNewPostBtn();
		deleteCookie();
		showSignInBar();
	}
	
	bool isValidName(name) {
		if(name == null)
			return false;
		RegExp exp = const RegExp(@"(^[\w0-9]+$)");
		return exp.hasMatch(name);
	}
	
	  void showSignInBar(){
		document.query('#singing').innerHTML = Windows.singInForm;
		document.query('#signbtn').on.click.add((events) => signIn());
	  }
	  
	  void showSignOutBar(){
		document.query('#singing').innerHTML = Windows.signOutForm(currUser);
		document.query('#signbtn').on.click.add((events) => signOut());
	  }

  
  
  void checkCookie(){
    String cook = getCookie();

	//window.alert("cook: " + cook);
	
    if(cook != null && cook != " "){
      currUser = cook;
    }
	//currUser = 'moshe';
  }
  
  String getCookie(){
    String cookie = document.cookie;
    String cookValue = cookie.substring(cookie.indexOf("=")+1);
    return cookValue;
  }
  
  void setCookie(String value){
    document.cookie = value;
  }
  
  void deleteCookie(){
    document.cookie = '';
	
	//window.alert("document.cookie: " + document.cookie);
  }
  
  
  
	void setPostRequester(PostsReq requester){
		postsRequest = requester;
	}
  
	bool isLogginedIn() => !(currUser == null || currUser == "");
	String getCurrentUser() => currUser;
	MakeNewPost getPostMaker() => newPostMaker;
	SideBar getSideBar() => bar;
	String getURL () => _url;
}
void main() {
	String location = window.location.host;
	Blog blog = new Blog("http://$location/prj"); 
	blog.showView();
}

